package com.android.task4;

import java.util.LinkedList;

public class ThreadPool {
	
//	poolSize - the number of threads to keep in the pool, even if they are idle.
	private int poolSize;
 

	private final PoolWorker[] threads;
	private final LinkedList queue;
	
	public ThreadPool(int threadPoolSize){
		poolSize =threadPoolSize;
		queue = new LinkedList();
		threads = new PoolWorker[poolSize];
		//Receiver puts request object into request queue of thread pool
		for (int i =0; i < poolSize; i++) {	
		threads[i] = new PoolWorker();
		threads[i].start();
		}
	}

	public int getPoolSize() {
		return poolSize;
	}


	public void execute(Runnable command){
		synchronized(queue){
			queue.addLast(command);
//			Use queue.notify() to waken up a currently sleeping thread
			queue.notify();
		}
	}
	
	
	private class PoolWorker extends Thread {

		@Override
		public void run() {
			Runnable job;
			//Idle worker thread removes request from request queue and starts processing
			while (true) {
				synchronized (queue) {
//					Worker threads have to check the synchronized queue if there is a job currently
//					available for processing
					while (queue.isEmpty()) {
						try {
								queue.wait();
						} catch (InterruptedException ignored) {}
						}
					job = (Runnable) queue.removeFirst();
				}
		
				try {
				new Thread(job).start();
				} catch (RuntimeException e) {
				// You might want to log something here
				}
			
		}
				
		}
		
	
	}
	public void stopRequestAllWorkers(){
		Runnable job;
		while(!queue.isEmpty()){
			job = (Runnable) queue.removeFirst();
			try {
				new Thread(job).start();
				} catch (RuntimeException e) {
				// You might want to log something here
				}
		}
	}
	

}




